package crm.model.teacherPC.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

import crm.model.Setting;
import crm.model.teacherPC.Manager;
import crm.model.teacherPC.connectList.StudentPcFinder;

public class NetLauncher implements Runnable {
	Manager manager;
	Thread thread;
	public NetLauncher(Manager manager) {
		this.manager=manager;
		(thread = new Thread(this)).start();
	}

	public void run() {
		while(true){
			try {
				System.out.println("netlauncher started");
				DatagramSocket udpSocket = new DatagramSocket(Setting.getReceivePort());
				udpSocket.setBroadcast(true);
				byte[] buffer = new byte[7];
				DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
				udpSocket.receive(packet);
				System.out.println("Receive: " + new String(packet.getData()));


				if (new String(packet.getData()).equals("Student")) {


					InetAddress inetA = packet.getAddress();
					udpSocket.close();


					DatagramSocket udpSocketSend = new DatagramSocket();

					buffer = new byte[0];
					packet = new DatagramPacket(buffer, buffer.length, inetA, Setting.getSendPort());
					udpSocketSend.send(packet);
					udpSocketSend.close();




					System.out.println("its a student: ");
					ServerSocket ss = StudentPcFinder.initServer();
					ss.setSoTimeout(10000);
					Socket s = ss.accept();
					StudentPC student = StudentPcFinder.connect(s, manager);
					manager.addStudent(student);
					manager.fireStudentAdded(student);
					ss.close();
				}
			} catch (SocketException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}catch (Exception e){
				System.out.println(e.getMessage());
				e.printStackTrace();
			}
		}
	}
}
